package com.blb.seckill.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.blb.seckill.entity.SeckillCourse;
import com.blb.seckill.mapper.SeckillCourseMapper;
import com.blb.seckill.service.SeckillCourseService;
import com.blb.seckill.util.Constants;
import com.learn.eduapi.util.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 秒杀服务实现类
 */
@Service
public class SeckillCourseServiceImpl extends ServiceImpl<SeckillCourseMapper, SeckillCourse> implements SeckillCourseService {

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 查询所有符合条件的秒杀商品,并保存到缓存中
     */
    @Override
    public List<SeckillCourse> loadSeckillCoursesToRedis() {
        SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date now = new Date();
        //查询合适的秒杀课程
        List<SeckillCourse> courses = this.list(new QueryWrapper<SeckillCourse>().lambda()
                .eq(SeckillCourse::getStatus, "1")  //状态必须为审核通过 status=1
                .gt(SeckillCourse::getStockCount, 0)       //商品库存个数>0
                .ge(SeckillCourse::getStartTime, format1.format(now)) //秒杀商品开始时间>=当前时间段
                .lt(SeckillCourse::getEndTime, format1.format(DateUtil.addDateHour(DateUtil.toDayStartHour(now), 24))));//秒杀商品开始时间是当日
        if(courses.size() > 0) {
            for (SeckillCourse course : courses) {
                //保存课程到Redis
                redisTemplate.boundHashOps(Constants.COURSE_KEY + DateUtil.getTodayString()).put(""+course.getId(),course);
                //保存课程库存到Redis
                redisTemplate.opsForValue().set(Constants.COURSE_STOCK_KEY + course.getId(),course.getStockCount());
            }
        }
        return courses;
    }

    @Override
    public List<SeckillCourse> getTodaySeckillCoursesFromRedis() {
        String key = Constants.COURSE_KEY + DateUtil.getTodayString();
        List<SeckillCourse> courses = (List<SeckillCourse>) redisTemplate.boundHashOps(key).values();
        return courses;
    }
}
